package com.eqdd.yiqidian.listener.rongyun;

import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.text.ClipboardManager;
import android.text.Selection;
import android.text.Spannable;
import android.view.View;
import android.widget.TextView;

import com.eqdd.yiqidian.base.AppConstent;
import com.eqdd.yiqidian.base.BaseApplication;
import com.eqdd.yiqidian.base.Config;
import com.eqdd.yiqidian.rongyun.message.mingpian.MingpianMessage;
import com.eqdd.yiqidian.share.JShareDialog;
import com.eqdd.yiqidian.share.JShareUtil;
import com.eqdd.yiqidian.share.TextShareBuilder;
import com.eqdd.yiqidian.ui.mine.UserCardActivity;
import com.eqdd.yiqidian.ui.mine.renwu.CreateRenwuActivity;
import com.eqdd.yiqidian.ui.mine.shenqing.CreateMemoActivity;
import com.eqdd.yiqidian.ui.share.ShareEnterActivity;
import com.eqdd.yiqidian.utils.CollectionUtil;

import io.rong.common.RLog;
import io.rong.imkit.RongContext;
import io.rong.imkit.RongIM;
import io.rong.imkit.manager.AudioPlayManager;
import io.rong.imkit.manager.SendImageManager;
import io.rong.imkit.userInfoCache.RongUserInfoManager;
import io.rong.imkit.utilities.OptionsPopupDialog;
import io.rong.imlib.model.Conversation;
import io.rong.imlib.model.Message;
import io.rong.imlib.model.UserInfo;
import io.rong.message.FileMessage;
import io.rong.message.ImageMessage;
import io.rong.message.LocationMessage;
import io.rong.message.TextMessage;
import io.rong.message.VoiceMessage;

/**
 * @author吕志豪 .
 * @date 18-2-6  下午3:30.
 * Github :https://github.com/lvzhihao100
 * E-Mail：1030753080@qq.com
 * 简书 :http://www.jianshu.com/u/6e525b929aac
 */

public class ConversationBehaviorListener implements RongIM.ConversationBehaviorListener {
    private static final String BEIWANGLU = "转入备忘录";
    private static final String RENWU = "转入任务";
    private static final String COPY = "复制";
    private static final String DELIVER = "发送给朋友/同事";
    private static final String COLLECTION = "收藏";
    private static final String DELETE = "删除";
    private static final String RECALL = "撤回消息";
    private static final String TITLE = "易企点";
    private Context context;
    private Intent intent;
    private String source;

    @Override
    public boolean onUserPortraitClick(Context context, Conversation.ConversationType conversationType, UserInfo userInfo) {
        Intent intent = new Intent(context, UserCardActivity.class);
        intent.putExtra(Config.GUID, userInfo.getUserId());
        context.startActivity(intent);
        return true;
    }

    @Override
    public boolean onUserPortraitLongClick(Context context, Conversation.ConversationType conversationType, UserInfo userInfo) {
        return false;
    }

    @Override
    public boolean onMessageClick(Context context, View view, Message message) {
        return false;
    }

    @Override
    public boolean onMessageLinkClick(Context context, String s) {
        return false;
    }

    @Override
    public boolean onMessageLongClick(Context context, View view, Message message) {
        showLongClickDialog(context, view, message);
        return true;
    }

    private void showLongClickDialog(Context context, View view, io.rong.imlib.model.Message message) {
        source = message.getConversationType() == Conversation.ConversationType.PRIVATE ? "私聊" : "群组";
        this.context = context;
        if (message.getContent() instanceof TextMessage) {//文字
            dealTextMeaasge(view, message);
        } else if (message.getContent() instanceof ImageMessage) {//图片
            dealImgMessage(view, message);
        } else if (message.getContent() instanceof FileMessage) {//文件
            dealFileMessage(view, message);
        } else if (message.getContent() instanceof VoiceMessage) {//语音
            dealVoiceMessage(view, message);
        } else if (message.getContent() instanceof LocationMessage) {//地图
            dealLocationMessage(view, message);
        } else if (message.getContent() instanceof MingpianMessage) {//名片
            dealMingpianMessage(view, message);
        } else {
            dealOther(view, message);
        }
    }

    @NonNull
    private boolean isCancel(io.rong.imlib.model.Message message) {
        long deltaTime = RongIM.getInstance().getDeltaTime();
        long normalTime = System.currentTimeMillis() - deltaTime;
        boolean enableMessageRecall = false;
        int messageRecallInterval = -1;
        boolean hasSent = !message.getSentStatus().equals(io.rong.imlib.model.Message.SentStatus.SENDING) && !message.getSentStatus().equals(io.rong.imlib.model.Message.SentStatus.FAILED);

        try {
            enableMessageRecall = RongContext.getInstance().getResources().getBoolean(io.rong.imkit.R.bool.rc_enable_message_recall);
            messageRecallInterval = RongContext.getInstance().getResources().getInteger(io.rong.imkit.R.integer.rc_message_recall_interval);
        } catch (Resources.NotFoundException var15) {
            RLog.e("TextMessageItemProvider", "rc_message_recall_interval not configure in rc_config.xml");
            var15.printStackTrace();
        }

        return (hasSent && enableMessageRecall && normalTime - message.getSentTime() <= (long) (messageRecallInterval * 1000) && message.getSenderUserId().equals(RongIM.getInstance().getCurrentUserId()) && !message.getConversationType().equals(Conversation.ConversationType.CUSTOMER_SERVICE) && !message.getConversationType().equals(Conversation.ConversationType.APP_PUBLIC_SERVICE) && !message.getConversationType().equals(Conversation.ConversationType.PUBLIC_SERVICE) && !message.getConversationType().equals(Conversation.ConversationType.SYSTEM) && !message.getConversationType().equals(Conversation.ConversationType.CHATROOM));
    }

    private void dealOther(View view, io.rong.imlib.model.Message message) {
        String[] items;
        if (isCancel(message)) {
            items = new String[]{DELETE, RECALL};
        } else {
            items = new String[]{DELETE};
        }
        showLongPressDialog(view, message, items, null);
    }

    private void dealMingpianMessage(View view, io.rong.imlib.model.Message message) {
        String[] items;
        if (isCancel(message)) {
            items = new String[]{DELIVER, DELETE, RECALL};
        } else {
            items = new String[]{DELIVER, DELETE};
        }
        showLongPressDialog(view, message, items, null);
    }

    private void dealLocationMessage(View view, io.rong.imlib.model.Message message) {
        String[] items;
        if (isCancel(message)) {
            items = new String[]{DELIVER, DELETE, RECALL};
        } else {
            items = new String[]{DELIVER, DELETE};
        }
        showLongPressDialog(view, message, items, null);
    }

    private void dealVoiceMessage(View view, io.rong.imlib.model.Message message) {
        String[] items;
        if (isCancel(message)) {
            items = new String[]{DELETE, RECALL};
        } else {
            items = new String[]{DELETE};
        }
        showLongPressDialog(view, message, items, null);
    }

    private void dealFileMessage(View view, io.rong.imlib.model.Message message) {
        long deltaTime = RongIM.getInstance().getDeltaTime();
        long normalTime = System.currentTimeMillis() - deltaTime;
        boolean enableMessageRecall = false;
        int messageRecallInterval = -1;

//        String realPathFromUri = FileProviderUtil.getRealPathFromUri(this, ((FileMessage) message.getContent()).getFileUrl());
//        String realFilePath = FileProviderUtil.getRealFilePath(this, ((FileMessage) message.getContent()).getFileUrl());
        try {
            enableMessageRecall = RongContext.getInstance().getResources().getBoolean(io.rong.imkit.R.bool.rc_enable_message_recall);
            messageRecallInterval = RongContext.getInstance().getResources().getInteger(io.rong.imkit.R.integer.rc_message_recall_interval);
        } catch (Resources.NotFoundException var13) {
            RLog.e("FileMessageItemProvider", "rc_message_recall_interval not configure in rc_config.xml");
            var13.printStackTrace();
        }
        if (!message.getSentStatus().equals(io.rong.imlib.model.Message.SentStatus.SENDING)) {
            String[] items;
            if (((FileMessage) message.getContent()).getLocalPath() == null) {
                items = new String[]{DELETE};

            } else if (message.getSentStatus().equals(io.rong.imlib.model.Message.SentStatus.SENT) && enableMessageRecall && normalTime - message.getSentTime() <= (long) (messageRecallInterval * 1000) && message.getSenderUserId().equals(RongIM.getInstance().getCurrentUserId()) && !message.getConversationType().equals(Conversation.ConversationType.CUSTOMER_SERVICE) && !message.getConversationType().equals(Conversation.ConversationType.APP_PUBLIC_SERVICE) && !message.getConversationType().equals(Conversation.ConversationType.PUBLIC_SERVICE) && !message.getConversationType().equals(Conversation.ConversationType.SYSTEM) && !message.getConversationType().equals(Conversation.ConversationType.CHATROOM)) {
                items = new String[]{DELIVER, DELETE, RECALL};
            } else {
                items = new String[]{DELIVER, DELETE};
            }

            showLongPressDialog(view, message, items, null);
        }
    }

    private void dealImgMessage(View view, io.rong.imlib.model.Message message) {
        String[] items;
        if (isCancel(message)) {
            items = new String[]{DELIVER, COLLECTION, DELETE, RECALL};
        } else {
            items = new String[]{DELIVER, COLLECTION, DELETE};
        }
        showLongPressDialog(view, message, items, null);

    }

    private void dealTextMeaasge(View view, io.rong.imlib.model.Message message) {
        if (view instanceof TextView) {
            CharSequence items = ((TextView) view).getText();
            if (items != null && items instanceof Spannable) {
                Selection.removeSelection((Spannable) items);
            }
        }
        String textContent = null;
        if (message.getContent() instanceof TextMessage) {
            textContent = ((TextMessage) message.getContent()).getContent();
        }
        String[] items1;
        if (isCancel(message)) {
            items1 = new String[]{BEIWANGLU, RENWU, COPY, DELIVER, COLLECTION, DELETE, RECALL};
        } else {
            items1 = new String[]{BEIWANGLU, RENWU, COPY, DELIVER, COLLECTION, DELETE,};
        }

        showLongPressDialog(view, message, items1, textContent);
    }

    private void showLongPressDialog(View view, io.rong.imlib.model.Message message, String[] items1, String textContent) {
        OptionsPopupDialog.newInstance(view.getContext(), items1).setOptionsPopupDialogListener(which -> {
            Bundle bundle = new Bundle();
            switch (items1[which]) {
                case BEIWANGLU:
                    if (message.getContent() instanceof TextMessage) {
                        bundle.putString(Config.CONTENT, textContent);
                        intent = new Intent(context, CreateMemoActivity.class);
                        intent.putExtras(bundle);
                        context.startActivity(intent);
                    }
                    break;
                case RENWU:
                    if (message.getContent() instanceof TextMessage) {
                        bundle.putString(Config.CONTENT, textContent);
                        intent = new Intent(context, CreateRenwuActivity.class);
                        intent.putExtras(bundle);
                        context.startActivity(intent);
                    }
                    break;
                case COPY:
                    if (message.getContent() instanceof TextMessage) {
                        ClipboardManager clipboard = (ClipboardManager) view.getContext().getSystemService(Context.CLIPBOARD_SERVICE);
                        clipboard.setText(textContent);
                    }
                    break;
                case DELIVER:
                    AppConstent.messageContent = message.getContent();
                    if (message.getContent() instanceof TextMessage) {
                        TextShareBuilder builder = new TextShareBuilder(context);
                        builder.setText(textContent)
                                .setTitle(message.getConversationType().equals(Conversation.ConversationType.PRIVATE) ? "单聊" : "群聊")
                                .setSource("聊天")
                                .setSourceOwner(message.getSenderUserId());
                        new JShareDialog(builder, context).show();
                    } else {
                        context.startActivity(new Intent(context, ShareEnterActivity.class));
                    }
                    break;
                case COLLECTION:
                    if (message.getContent() instanceof TextMessage) {
                        CollectionUtil.INSTANCE.chooseText(
                                "我的收藏",
                                textContent,
                                source,
                                message.getContent().getUserInfo().getUserId());
                    } else if (message.getContent() instanceof ImageMessage) {
                        CollectionUtil.INSTANCE.chooseImg(
                                ((ImageMessage) message.getContent()).getMediaUrl().toString(),
                                source,
                                message.getContent().getUserInfo().getUserId());
                    }
                    break;
                case DELETE:
                    if (message.getContent() instanceof VoiceMessage) {
                        AudioPlayManager.getInstance().stopPlay();
                    } else if (message.getContent() instanceof FileMessage) {
                        RongIM.getInstance().cancelSendMediaMessage(message, null);
                    } else if (message.getContent() instanceof ImageMessage) {
                        SendImageManager.getInstance().cancelSendingImage(message.getConversationType(), message.getTargetId(), message.getMessageId());

                    }
                    RongIM.getInstance().deleteMessages(new int[]{message.getMessageId()}, null);
                    break;
                case RECALL:
                    RongIM.getInstance().recallMessage(message, getPushContent(view.getContext(), message));
                    break;

            }
        }).show();
    }

    private String getPushContent(Context context, io.rong.imlib.model.Message message) {
        String userName = "";
        UserInfo userInfo = RongUserInfoManager.getInstance().getUserInfo(message.getSenderUserId());
        if (userInfo != null) {
            userName = userInfo.getName();
        }

        return context.getString(io.rong.imkit.R.string.rc_user_recalled_message, userName);
    }
}
